package coursetest;

import banksimulator.bank.AbstractAccount;
import banksimulator.bank.AbstractBank;
import banksimulator.bank.NoSuchAccountException;
import java.util.Iterator;
import java.util.TreeMap;

/**
 * 这是一个AbstractBank的实现，它使用TreeMap来储存多个帐户。
 * @author Rajab
 */
public class MemoryBank extends AbstractBank {

    //存储帐户用
    private TreeMap<String, AbstractAccount> storage;
    //银行名称
    private String name;

    /**
     * 建立一个指定名称的银行。
     * @param name 银行的名称
     */
    public MemoryBank(String name) {
        //存放帐户
        storage = new TreeMap<String, AbstractAccount>();
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public AbstractAccount getAccount(String accountID) throws NoSuchAccountException {
        if (!isExists(accountID)) {
            throw new NoSuchAccountException(accountID);
        } else {
            return storage.get(accountID);
        }
    }

    public void addAccount(AbstractAccount account) {
        if (isExists(account)) {
            return;
        }
        storage.put(account.getAccountID(), account);
        fireAccountAdded(account.getAccountID());
    }

    public boolean isExists(AbstractAccount account) {
        if (account == null) {
            return false;
        } else {
            return isExists(account.getAccountID());
        }
    }

    public boolean isExists(String accountID) {
        return storage.containsKey(accountID);
    }

    public int size() {
        return storage.size();
    }

    public Iterator<AbstractAccount> iterator() {
        return storage.values().iterator();
    }

    public void removeAccount(AbstractAccount account) throws NoSuchAccountException {
        if (account == null) {
            return;
        }
        removeAccount(account.getAccountID());
    }

    public void removeAccount(String accountID) throws NoSuchAccountException {
        if (accountID == null) {
            return;
        }
        if (!storage.containsKey(accountID)) {
            throw new NoSuchAccountException(accountID);
        } else {
            storage.remove(accountID);
            fireAccountRemoved(accountID);
        }
    }

    public AbstractAccount getAccount(int index) throws IndexOutOfBoundsException {
        if (index < 0 || index > storage.size() - 1) {
            throw new IndexOutOfBoundsException();
        }
        return storage.get((String) storage.keySet().toArray()[index]);
    }
}
